import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import { DICT_TYPE } from '@vben/constants';
import { formatDateTime, handleTree } from '@vben/utils';

import { getDeptListCondition } from '#/api/system/dept';
import { getOAuth2ClientList } from '#/api/system/oauth2/client';
import { DictTag } from '#/components/dict-tag';
import { getRangePickerDefaultProps } from '#/utils';

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入用户名称',
      },
    },
    {
      fieldName: 'userIp',
      label: '登录地址',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入登录地址',
      },
    },
    {
      fieldName: 'clientId',
      label: '应用名称',
      component: 'ApiSelect',
      componentProps: {
        api: getOAuth2ClientList,
        labelField: 'name',
        valueField: 'clientId',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'unitId',
      label: '单位',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        componentProps: (values) => {
          return {
            // 关键：用 areaCode 作为 key，强制重新渲染
            key: values.areaCode || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'unit',
                ...(values.areaCode ? { areaCode: values.areaCode } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择单位',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('unitId', undefined);
        },
      },
    },
    {
      fieldName: 'deptId',
      label: '归属部门',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['unitId'],
        componentProps: (values) => {
          return {
            // 关键：用 unitId 作为 key，强制重新渲染
            key: values.unitId || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'dept',
                ...(values.unitId ? { unitId: values.unitId } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择归属部门',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('deptId', undefined);
        },
      },
    },
    {
      fieldName: 'createTime',
      label: '登录时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      field: 'id',
      title: '日志编号',
      minWidth: 100,
    },
    {
      field: 'logType',
      title: '操作类型',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.SYSTEM_LOGIN_TYPE },
      },
    },
    {
      field: 'username',
      title: '用户名称',
      minWidth: 180,
    },
    {
      field: 'userIp',
      title: '登录地址',
      minWidth: 180,
    },
    {
      field: 'userAgent',
      title: '浏览器',
      minWidth: 200,
    },
    {
      field: 'result',
      title: '登录结果',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.SYSTEM_LOGIN_RESULT },
      },
    },
    {
      field: 'createTime',
      title: '登录日期',
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      field: 'areaName',
      title: '所属区域',
      minWidth: 120,
    },
    {
      field: 'unitName',
      title: '所属单位',
      minWidth: 120,
    },
    {
      field: 'deptName',
      title: '所属部门',
      minWidth: 120,
    },
    {
      field: 'appName',
      title: '所属应用',
      minWidth: 120,
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      field: 'id',
      label: '日志编号',
    },
    {
      field: 'logType',
      label: '操作类型',
      render: (val) => {
        return h(DictTag, {
          type: DICT_TYPE.SYSTEM_LOGIN_TYPE,
          value: val,
        });
      },
    },
    {
      field: 'username',
      label: '用户名称',
    },
    {
      field: 'userIp',
      label: '登录地址',
    },
    {
      field: 'userAgent',
      label: '浏览器',
    },
    {
      field: 'result',
      label: '登录结果',
      render: (val) => {
        return h(DictTag, {
          type: DICT_TYPE.SYSTEM_LOGIN_RESULT,
          value: val,
        });
      },
    },
    {
      field: 'createTime',
      label: '登录日期',
      render: (val) => formatDateTime(val) as string,
    },
    {
      field: 'areaName',
      label: '所属区域',
    },
    {
      field: 'unitName',
      label: '所属单位',
    },
    {
      field: 'deptName',
      label: '所属部门',
    },
    {
      field: 'appName',
      label: '所属应用',
    },
  ];
}
